package top.luo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author luo
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        // 创建两个线程池对象
        // bossGroup 负载接收用户连接
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // workerGroup 负载处理用户IO读写
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        // 创建启动引导类
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 设置启动引导类
        // 添加两个线程池, 第一个线程池负责接收, 第二个线程池负责读写
        serverBootstrap
                .group(bossGroup, workerGroup)
                // 设置通道类型
                .channel(NioServerSocketChannel.class)
                // 绑定一个初始化监听
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    // channel事件监听
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 获取pipeline
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline
                                // 绑定编码
                                .addFirst(new StringEncoder())
                                .addLast(new StringDecoder())
                                // 绑定业务处理类
                                .addLast(new SimpleChannelInboundHandler<String>() {
                                    @Override
                                    protected void channelRead0(ChannelHandlerContext context, String s) throws Exception {
                                        System.out.println(s);
                                    }
                                });
                    }
                });

        // 启动引导类绑定端口
        ChannelFuture channelFuture = serverBootstrap.bind(8081).sync();

        // 关闭通道
        channelFuture.channel().closeFuture();
    }

}
